package cn.android666.audiorecorder

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PowerManager
import cn.android666.audiorecorder.databinding.ActivityMainBinding
import cn.android666.audiorecorder.permission.PermissionUtil
import timber.log.Timber

class MainActivity : AppCompatActivity() {

    private val powerManager: PowerManager by lazy { getSystemService(Context.POWER_SERVICE) as PowerManager }
    private val wakeLock: PowerManager.WakeLock by lazy { powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MainActivity:MyTag") }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        PermissionUtil.registerForActivityResult(this)

        binding.startRecordButton.setOnClickListener {
            PermissionUtil.requestPermission(this) {
                AudioRecorder.startRecord()
            }
        }

        binding.stopRecordButton.setOnClickListener {
            AudioRecorder.stopRecord()
        }

        if (!wakeLock.isHeld) {
            wakeLock.acquire()
            Timber.i("获取唤醒锁")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (wakeLock.isHeld) {
            wakeLock.release()
            Timber.i("释放唤醒锁")
        }
    }

}